package com.cjb.cloudsystem.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cjb.cloudsecurity.userMsg.entity.UserDetail;
import com.cjb.cloudsystem.entity.SysUser;
import com.cjb.cloudsystem.service.SysUserService;
import com.cjb.cloudsystem.vo.EditPassword;
import com.cjb.cloudsystem.vo.FileVO;
import com.cjb.cloudsystem.vo.SysUserVO;
import com.cjb.cloudsystem.vo.UsersExcelVO;
import com.cjb.common.common.excel.ExcelUtil;
import com.cjb.common.exception.ServerException;
import com.cjb.common.util.Common;
import com.cjb.common.util.HttpContextUtils;
import com.cjb.common.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @Author 1.0.0 2023-09-23
 * @Package IntelliJ IDEA
 * @Class SysUserControl
 * @Date 2023-09-23
 */
@RestController
@Tag(name = "sys/user")
@RequestMapping(value = {"sys/user"})
@ApiResponses(@ApiResponse(responseCode = "200", description = "接口请求成功"))
@Slf4j
public class SysUserController extends ExcelUtil {
    /*
     * 注入事物类
     */
    @Autowired
    private SysUserService sysUserService;

    /**
     * 注入文件目录地址
     */
    @Value("${headPicDir}")
    private String headPicDir;

    /**
     * 单个保存
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @PutMapping("/save")
    @Operation(summary = "单个保存")
    public Result<Boolean> save(@RequestBody SysUser sysUser) {
        return Result.success(sysUserService.save(sysUser));
    }

    /**
     * 批量保存
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @PostMapping("/listSave")
    @Operation(summary = "批量保存")
    public Result<Integer> listSave(@RequestBody List<SysUser> sysUser) {
        return Result.success(sysUserService.listSave(sysUser));
    }

    /**
     * 单个查询
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @GetMapping("{id}")
    @Operation(summary = "单个查询-通过ID")
    public Result<SysUser> queryById(@PathVariable("id") Long id) {
        return Result.success(sysUserService.queryById(id));
    }

    /**
     * 分页查询
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询-通过页码")
    public Result<Page<SysUser>> queryPage(@ParameterObject @Valid SysUserVO sysUser){
        Page sysUserPage = new Page<SysUser>(sysUser.getPage(),sysUser.getLimit());
        return Result.success( sysUserService.queryPage(sysUserPage,sysUser));
    }

    /**
     * 批量更新
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @PostMapping("/listUpdate")
    @Operation(summary = "批量更新")
    public Result<String> listUpdate(@RequestBody List<SysUser> sysUser) {
        sysUserService.listUpdate(sysUser);
        return Result.success();
    }


    /**
     * 批量删除
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @PostMapping("/listDelete")
    @Operation(summary = "批量删除")
    public Result<String> listDelete(@RequestBody List<SysUser> sysUser) {
        log.info("打印请求参数 {}",sysUser);
        sysUserService.listDelete(sysUser);
        return Result.success();
    }

    /**
     * 通过id删除
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @PostMapping("/deleteById")
    @Operation(summary = "单个删除-通过ID")
    public Result<String> deleteById(@RequestBody SysUser sysUser) {
        sysUserService.deleteById(sysUser);
        return Result.success();
    }

    /**
     * 返回全部信息
     *
     * @Author 1.0.0 2023-09-23
     * @Value
     * @Title
     */
    @PostMapping("/returnAllData")
    @Operation(summary = "返回所有信息")
    public Result<List<SysUser>> returnAllData() {
        return Result.success(sysUserService.returnAllData());
    }

    /**
     * info
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @GetMapping("/info")
    @Operation(summary = "返回所有信息")
    public Result<UserDetail> info() {
        return Result.success(sysUserService.getUser());
    }

    /**
     * 密码修改
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @PostMapping("/password")
    @Operation(summary = "修改密码")
    public Result<UserDetail> password(@RequestBody EditPassword editPassword) {
        return Result.success(sysUserService.editPassword(editPassword));
    }

    /**
     * 更换头像
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @PostMapping("/change/picture")
    @Operation(summary = "更换头像")
    public Result<FileVO> changePicture(MultipartFile file,Long userId) {
        log.info("文件接受");
        String dir=headPicDir+ UUID.randomUUID();
        log.info("打印UUID {}",dir);
        if (Common.isEmpty(file)){
            throw new ServerException("文件是空的");
        }
        //文件后缀
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null && !originalFilename.isEmpty()) {
            int lastDotIndex = originalFilename.lastIndexOf('.');
            if (lastDotIndex > 0) {
              dir+="."+originalFilename.substring(lastDotIndex + 1);
            }

        }
        //设置头像文件目录
        try {
            return Result.success(sysUserService.upload(file, dir, userId));
        } catch (Exception e) {
            throw new ServerException("文件上传时发现异常" + e.getMessage());
        }
    }

    /**
     * 数据导出
     *
     * @Author chenjinbin
     * @Value
     * @Title
     */
    @GetMapping("/export/usermsg")
    @Operation(summary = "数据导出")
    public void exportUserMsg(@ParameterObject @Valid SysUserVO sysUser) {
        log.info("文件接受");
        List<SysUser> sysUsers = sysUserService.queryList(sysUser);
        List<UsersExcelVO> usersExcelVOList = new ArrayList<>();
        if (Common.isNotEmpty(sysUsers)) {

            sysUsers.forEach(user -> {
                UsersExcelVO usersExcelVO = new UsersExcelVO();
                try {
                    Common.copyNonNullProperties(user, usersExcelVO);
                    Optional.ofNullable(usersExcelVO).ifPresent(usersExcelVOList::add);
                } catch (Throwable e) {
                    log.info("复制找不到值");
                }
            });
            if (Common.isNotEmpty(usersExcelVOList)) {
                this.exportToExcel(usersExcelVOList, UsersExcelVO.class, HttpContextUtils.getHttpServletResponse(), "用户数据表" + DateUtil.now(), "用户数据");
            } else {
                new ServerException("导出数据为可空");
            }
            log.info("执行了导出操作");
        }
    }
}
